<?php
/**
 * Application View class file
 *
 * @package Apricot
 */

/**
 * Application View
 *
 * @uses Apricot_View
 * @package Apricot
 * @author Jansen Price <jansen.price@gmail.com>
 * @version $Id$
 */
class ApplicationView extends Apricot_View
{
    /**
     * useLayout
     *
     * @var mixed
     */
    public $useLayout = true;

    /**
     * The layout template name
     * 
     * @var string
     */
    protected $_layout = 'layout.phtml';

    protected $_activeNavigation = '';
    protected $_userAgent        = '';
    protected $_requestDefaults  = array();

    /**
     * init
     *
     * @return void
     */
    public function preAssemble()
    {
        $ak = $this->_kernel;
        /*if ($ak->getConfig('www_root')) {
            $this->setBaseUrl($ak->getConfig('www_root'));
            $this->setBase($this->_getDomain(false) . $this->getBaseUrl());
        }*/

        $this->_userAgent = $ak->getRequest()
            ->getHeaderParam('USER_AGENT');

        //$this->setCssfile('css/style-default.css');

        //if ($this->_kernel->getConfig('env') == 'production') {
        //    $this->setGoogleTrackingCode('UA-xxxxx');
        //}
    }

    /**
     * Create the page layout
     *
     * @param string $content The body content
     * @return void
     */
    public function assemble($content)
    {
        $this->content = $content;

        if ($this->useLayout) {
            $appRoot  = $this->_kernel->getConfig('app_root');
            $viewsDir = $this->_kernel->getConfig('views_dir');

            $layoutFile = $appRoot . DIRECTORY_SEPARATOR
                . $viewsDir . 'templates' . DIRECTORY_SEPARATOR
                . $this->_layout;

            if (file_exists($layoutFile)) {
                $layout = $this->getIncludeContents($layoutFile);
            } else {
                $layout = $this->_engine->content;
            }
            $this->_engine->setBody($layout);
        } else {
            $this->_engine->setBody($content);
        }

        $this->initGoogleAnalytics();
    }

    /**
     * Set layout template name
     * 
     * @param string $name Name or filename
     * @return void
     */
    public function setLayout($name)
    {
        $this->_layout = $name;

        if (strpos($name, '.phtml') === false) {
            $this->_layout .= '.phtml';
        }
    }

    /**
     * Escape characters
     *
     * @param mixed $text Text to escape
     * @return string
     */
    public function escape($text)
    {
        $out = str_replace('"', '\\"', $text);
        return $out;
    }

    /**
     * Special class to set the Google Analytics tracking code for this page
     *
     * @param string $code The Google Analytics tracking code
     * @param array $options Other options to set for Google Analytics
     * @return void
     */
    public function setGoogleTrackingCode($code, $options=array())
    {
        $this->setParam('ga_tracking_code', $code);

        // One domain with multiple subdomains
        if (isset($options['ga_domain_name'])) {
            // should be set, for example, to ".domain.com"
            $this->setParam('ga_domain_name', $options['ga_domain_name']);
        }

        // For multiple top-level domains
        if (isset($options['ga_allow_linker'])) {
            // should be set to 'true' or 'false' or left blank
            $this->setParam('ga_allow_linker', $options['ga_allow_linker']);
        }
    }

    /**
     * Set the appropriate javascript to initialize Google Analytics
     * tracking
     *
     * This will only add the javascript if the code has been set
     * with set_google_tracking_code()
     *
     * @return void
     */
    public function initGoogleAnalytics()
    {
        if (null !== $this->getParam('ga_tracking_code')) {
            // google analytics
            $this->setJs(
                'var gaJsHost = (("https:" == document.location.protocol) '
                . '? "https://ssl." : "http://www.");' . "\n"
                . '    document.write(unescape("%3Cscript src=\'" + gaJsHost '
                . '+ "google-analytics.com/ga.js\' '
                . 'type=\'text/javascript\'%3E%3C/script%3E"));',
                'body'
            );
            $js = 'try {' . "\n"
                .'    var pageTracker = _gat._getTracker("'
                . $this->getParam('ga_tracking_code')
                . '");';

            if (null !== $this->getParam('ga_domain_name')) {
                $js .= 'pageTracker._setDomainName("'
                    . $this->getParam('ga_domain_name')
                    . '");';
            }

            if (null !== $this->getParam('ga_allow_linker')
                && $this->getParam('ga_allow_linker')
            ) {
                $js .= 'pageTracker._setAllowLinker(true);';
            }

            $js .= 'pageTracker._trackPageview();' . "\n"
                .'} catch(err) {}';

            $this->setJs($js, 'body');
        }
    }

    /**
     * Return the active navigation if set, otherwise
     * return the value inputed
     *
     * @param string $active The active navigation string
     * @return string
     */
    protected function _getActiveNavigation($active = null)
    {
        if (null === $active) {
            return $this->_activeNavigation;
        }
        return $active;
    }

    /**
     * _get_default_action
     *
     * @return string
     */
    protected function _getDefaultAction()
    {
        if (isset($this->_requestDefaults['action'])) {
            return $this->_requestDefaults['action'];
        } else {
            return 'index';
        }
    }

    /**
     * Generate an internal url
     *
     * @param mixed $input The string or array of whither to redirect
     * @param bool $reset Whether to reset request parameters
     * @param bool $xhtml Flag to indicate output is xhtml
     * @return string
     */
    public function url($input=null, $reset=false, $xhtml=true)
    {
        if ($input == null) {
            return '';
        }

        $default_params = array(
            'action' => $this->_getDefaultAction()
        );

        return $this->_kernel->getRequest()
            ->generateUrl($input, $default_params, $reset, $xhtml);
    }

    /**
     * Get the domain name for the current site
     *
     * @param boolean $ending_slash Include the ending slash
     * @return string
     */
    protected function _getDomain($ending_slash = false)
    {
        $protocol = 'http';
        if (isset($_SERVER['SERVER_PROTOCOL'])) {
            if (strpos($_SERVER['SERVER_PROTOCOL'], 'HTTPS')) {
                $protocol = 'https';
            }
        }

        $host = "localhost";
        if (isset($_SERVER['HTTP_HOST'])) {
            $host = $_SERVER['HTTP_HOST'];
        }

        $out = $protocol . "://" . $host;
        if ($ending_slash) {
            $out .= "/";
        }

        return $out;
    }

    /**
     * Return a fully qualified url for the inputed url
     *
     * todo Add support for https
     *
     * @param string $url The url to fully qualify
     * @return string
     */
    protected function _fullyQualifyUrl($url)
    {
        if (substr($url, 0, 7) != 'http://') {
            $url = 'http://' . $url;
        }
        return $url;
    }

    /**
     * Return whether the client is an iPhone or iPod touch.
     *
     * @return int
     */
    public function isIphone()
    {
        return strpos($this->_userAgent, 'iPhone');
    }
}
